package com.science.slam.controller;

import com.science.slam.domain.User;
import com.science.slam.exception.BusinessException;
import com.science.slam.exception.ErrorCode;
import com.science.slam.request.LikeRequestBody;
import com.science.slam.response.BasicResponse;
import com.science.slam.service.LikeTableService;
import com.science.slam.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
public class LikeController {
    @Autowired
    UserService userService;
    @Autowired
    LikeTableService likeService;

    @PostMapping("/like")
    public BasicResponse<String> doLike(@RequestBody LikeRequestBody body, HttpServletRequest request) {
        User currentUser = userService.getCurrentUser(request);
        if (currentUser == null)
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        String userID = body.getUserID();
        if (!currentUser.getAccount().equals(userID))
            throw new BusinessException(ErrorCode.NO_PERMISSIONS);
        String fileID = body.getFileID();
        Integer res = likeService.UnLike(userID, fileID);
        if (res == 1) {
            return BasicResponse.success("取消点赞成功");
        }
        Integer like = likeService.Like(userID, fileID);
        if (like != 1) {
            throw new BusinessException(ErrorCode.DATABASE_ERROR);
        }
        return BasicResponse.success("点赞成功");
    }
}
